﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Web.Framework.Translate;
using System.IO;
using Web.CrmContacto.Code;
using Web.Framework.Svc;
using CrmContacto.WebApp.Code.InnerClasses.FrontEnd;
using Web.Framework;
using CrmContacto.Contracts.Contracts.Misc;
using CrmContacto.WebApp.Code.InnerClasses;
using System.Configuration;
using Web.Framework.Exceptions;

namespace CrmContacto.WebApp.Handler
{
    /// <summary>
    /// Summary description for FileUploadCustomers
    /// </summary>
    public class FileUploadCustomers : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string response = LocalizationProvider.Instance["Bo.Excel.Contacto.ArchivoProcesadoCorrectamente"];
            string filePath = string.Empty;
            List<string> parseErrors = new List<string>();
            try
            {
                string fileName = Path.GetFileName(context.Request.Files[0].FileName);
                string tmpPath = HttpContext.Current.Server.MapPath("/Tmp");
                fileName = fileName + Guid.NewGuid().ToString();
                filePath = Path.Combine(tmpPath, fileName);
                context.Request.Files[0].SaveAs(filePath);

                WebServiceHelper webServiceHelper = new WebServiceHelper();
                webServiceHelper.ServiceOptionsDefault = new ServiceOptions();
                webServiceHelper.ServiceOptionsDefault.UserName = Convert.ToString(context.User.Identity.Name);

                ExcelHelperContactosParam excelContactosParam = new ExcelHelperContactosParam();
                excelContactosParam.EmpresaId = BasePage.CompanyId;
                excelContactosParam.Categorias = BasePage.GetCategorias(context, BasePage.CompanyId);
                excelContactosParam.Paises = BasePage.GetPaises(context);

                int paisId = Convert.ToInt32(ConfigurationManager.AppSettings["paisPorDefecto"]);
                excelContactosParam.Provincias = BasePage.GetProvincias(context, paisId);
                excelContactosParam.TiposDeDocumento = BasePage.GetTipoDocumento(context, 0);

                List<ClienteWrap> clienteList = ExcelHelper.ObtenerContactos(filePath, excelContactosParam);

                clienteList = webServiceHelper.SaveCustomerList(clienteList);

                // Guardo en sessión lo procesado para que se vea desde la pantalla
                context.Cache.Add(context.Session.SessionID + MiscClass.CustomerImportRecordsKey, clienteList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(2, 0, 0), System.Web.Caching.CacheItemPriority.Low, null);

            }
            //catch (FaultException<WebFrameworkFaultException> ex)
            //{
            //    response = ex.Detail.Message;
            //    ExceptionManager.Instance.HandleException(ex);
            //}
            catch (Exception ex)
            {
                response = ex.GetExceptionMessage() + ex.GetExceptionStackTrace();
                ExceptionManager.Instance.HandleException(ex);
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }

            context.Response.ClearContent();
            context.Response.Write(response);
        }

        private static string BuildErrorResponse(List<string> parseErrors, List<string> ingresoDeProductosInValidados)
        {
            string response = string.Empty;
            //StringBuilder builder = new StringBuilder();
            //if (parseErrors.Count > 0 || ingresoDeProductosInValidados.Count > 0)
            //{
            //    foreach (string errorParseo in parseErrors)
            //    {
            //        builder.AppendLine(errorParseo);
            //    }

            //    if (ingresoDeProductosInValidados.Count > 0)
            //    {
            //        builder.AppendLine("Los siguientes valores no existen en la base de datos:");
            //        foreach (string errorNoExistencia in ingresoDeProductosInValidados)
            //        {

            //            builder.AppendLine(errorNoExistencia);
            //        }
            //    }

            //    response = builder.ToString();
            //}
            return response;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}